from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from .models import Objective, KeyResult, CheckIn, Team, Comment

class RegisterSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, required=True, validators=[validate_password])
    password2 = serializers.CharField(write_only=True, required=True)

    class Meta:
        model = User
        fields = ('username', 'password', 'password2', 'email', 'first_name', 'last_name')

    def validate(self, attrs):
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError({"password": "两次密码不匹配"})
        return attrs

    def create(self, validated_data):
        validated_data.pop('password2')
        user = User.objects.create_user(**validated_data)
        return user

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'first_name', 'last_name']
        extra_kwargs = {
            'username': {'required': False},
            'email': {'required': False}
        }


class CommentSerializer(serializers.ModelSerializer):
    created_by = UserSerializer(read_only=True)
    
    class Meta:
        model = Comment
        fields = ['id', 'content', 'created_by', 'created_at', 'objective', 'key_result']
        read_only_fields = ['created_at']


class CheckInSerializer(serializers.ModelSerializer):
    created_by = UserSerializer(read_only=True)
    
    class Meta:
        model = CheckIn
        fields = ['id', 'key_result', 'date', 'previous_progress', 'current_progress', 
                  'notes', 'created_by', 'created_at']
        read_only_fields = ['created_at']


class KeyResultSerializer(serializers.ModelSerializer):
    assignee = UserSerializer(read_only=True)
    assignee_id = serializers.IntegerField(write_only=True, required=False, allow_null=True)
    check_ins = CheckInSerializer(many=True, read_only=True)
    comments = CommentSerializer(many=True, read_only=True)
    
    class Meta:
        model = KeyResult
        fields = ['id', 'objective', 'title', 'description', 'assignee', 'assignee_id',
                  'progress', 'status', 'created_at', 'updated_at', 'check_ins', 'comments']
        read_only_fields = ['created_at', 'updated_at']
    
    def create(self, validated_data):
        assignee_id = validated_data.pop('assignee_id', None)
        if assignee_id:
            try:
                assignee = User.objects.get(pk=assignee_id)
                validated_data['assignee'] = assignee
            except User.DoesNotExist:
                pass
        return super().create(validated_data)
    
    def update(self, instance, validated_data):
        assignee_id = validated_data.pop('assignee_id', None)
        if assignee_id:
            try:
                assignee = User.objects.get(pk=assignee_id)
                validated_data['assignee'] = assignee
            except User.DoesNotExist:
                pass
        return super().update(instance, validated_data)


class ObjectiveSerializer(serializers.ModelSerializer):
    owner = UserSerializer(read_only=True)
    owner_id = serializers.IntegerField(write_only=True, required=False)
    key_results = KeyResultSerializer(many=True, read_only=True)
    comments = CommentSerializer(many=True, read_only=True)
    # 添加父子关系字段
    parent = serializers.PrimaryKeyRelatedField(queryset=Objective.objects.all(), required=False, allow_null=True)
    children = serializers.SerializerMethodField()
    breadcrumb = serializers.SerializerMethodField()
    # 明确定义日期字段，确保正确处理日期格式
    start_date = serializers.DateField(required=False)
    end_date = serializers.DateField()

    def get_children(self, obj):
        """获取子目标的简要信息"""
        children = obj.children_summary
        return children

    def get_breadcrumb(self, obj):
        """获取目标的层级路径"""
        path = []
        for objective in obj.breadcrumb:
            path.append({
                'id': objective.id,
                'title': objective.title,
                'level': objective.level
            })
        return path
    
    class Meta:
        model = Objective
        fields = ['id', 'title', 'description', 'owner', 'owner_id', 'start_date', 'end_date',
                  'status', 'created_at', 'updated_at', 'key_results', 'comments',
                  'parent', 'children', 'breadcrumb', 'level']
        read_only_fields = ['created_at', 'updated_at']
    
    def create(self, validated_data):
        owner_id = validated_data.pop('owner_id', None)
        if owner_id:
            try:
                owner = User.objects.get(pk=owner_id)
                validated_data['owner'] = owner
            except User.DoesNotExist:
                pass
        else:
            # 如果没有指定owner_id，则使用当前用户
            request = self.context.get('request')
            if request and hasattr(request, 'user'):
                validated_data['owner'] = request.user
        
        return super().create(validated_data)
    
    def update(self, instance, validated_data):
        owner_id = validated_data.pop('owner_id', None)
        if owner_id:
            try:
                owner = User.objects.get(pk=owner_id)
                validated_data['owner'] = owner
            except User.DoesNotExist:
                pass
        return super().update(instance, validated_data)


class TeamSerializer(serializers.ModelSerializer):
    leader = UserSerializer(read_only=True)
    leader_id = serializers.IntegerField(write_only=True, required=False, allow_null=True)
    members = UserSerializer(many=True, read_only=True)
    member_ids = serializers.ListField(
        child=serializers.IntegerField(),
        write_only=True,
        required=False
    )
    
    class Meta:
        model = Team
        fields = ['id', 'name', 'description', 'leader', 'leader_id', 
                  'members', 'member_ids', 'created_at']
        read_only_fields = ['created_at']
    
    def create(self, validated_data):
        leader_id = validated_data.pop('leader_id', None)
        member_ids = validated_data.pop('member_ids', [])
        
        team = Team.objects.create(**validated_data)
        
        if leader_id:
            try:
                leader = User.objects.get(pk=leader_id)
                team.leader = leader
                team.save()
            except User.DoesNotExist:
                pass
        
        if member_ids:
            members = User.objects.filter(pk__in=member_ids)
            team.members.set(members)
        
        return team
    
    def update(self, instance, validated_data):
        leader_id = validated_data.pop('leader_id', None)
        member_ids = validated_data.pop('member_ids', None)
        
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        
        if leader_id:
            try:
                leader = User.objects.get(pk=leader_id)
                instance.leader = leader
            except User.DoesNotExist:
                pass
        
        if member_ids is not None:
            members = User.objects.filter(pk__in=member_ids)
            instance.members.set(members)
        
        instance.save()
        return instance